<template>
  <div class="chart-container">
    <div class="header">
      <h2>空气质量趋势分析（折线图）</h2>
      <div class="filter-area">
        <el-select 
          v-model="selectedSite" 
          placeholder="选择检测点"
          clearable
          class="filter-select"
        >
          <el-option
            v-for="item in siteOptions"
            :key="item.site_id"
            :label="item.fullName"
            :value="item.site_id"
          />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="date-picker"
        />
      </div>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import * as echarts from 'echarts'
import { getAirDataBySiteId, getAirDataList } from '@/api/airData'
import { getFamilyList } from '@/api/family'
import { getSiteList } from '@/api/site'
import { getRoomList } from '@/api/room'

const chartRef = ref(null)
let chart = null

const familyList = ref([])
const siteList = ref([])
const roomList = ref([])
const selectedSite = ref('')
const dateRange = ref([])

// 处理检测点选项
const siteOptions = computed(() => {
  return siteList.value.map(site => {
    const room = roomList.value.find(r => r.room_id === site.room_id)
    const family = room ? familyList.value.find(f => f.family_id === room.family_id) : null
    return {
      site_id: site.site_id,
      fullName: `${family?.family_name || '未知家庭'}-${room?.room_name || '未知房间'}-${site.site_name}`
    }
  })
})

// 初始化图表
const initChart = () => {
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value)
}

// 更新图表数据
const updateChart = async () => {
  try {
    let data
    if (selectedSite.value) {
      const res = await getAirDataBySiteId(selectedSite.value)
      data = res.data
    } else {
      const res = await getAirDataList()
      data = res.data
    }

    // 如果选择了日期范围，过滤数据
    if (dateRange.value?.length === 2) {
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      data = data.filter(item => {
        const itemDate = new Date(item.recorded_at)
        return itemDate >= startDate && itemDate <= endDate
      })
    }

    // 按时间排序
    data.sort((a, b) => new Date(a.recorded_at) - new Date(b.recorded_at))

    const times = data.map(item => item.recorded_at)
    const metrics = ['pm25', 'pm10', 'temperature', 'humidity', 'formaldehyde']
    const series = metrics.map(metric => ({
      name: getMetricName(metric),
      type: 'line',
      data: data.map(item => Number(item[metric].toFixed(2))),
      yAxisIndex: getYAxisIndex(metric)
    }))

    // 更新图表配置
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: metrics.map(getMetricName)
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: times,
        axisLabel: {
          interval: 'auto',
          rotate: 45
        }
      },
      yAxis: [
        {
          type: 'value',
          name: 'PM2.5/PM10(μg/m³)',
          position: 'left'
        },
        {
          type: 'value',
          name: '温度(°C)/湿度(%)',
          position: 'right'
        },
        {
          type: 'value',
          name: '甲醛(mg/m³)',
          position: 'right',
          offset: 80
        }
      ],
      series
    }

    chart.setOption(option)
  } catch (error) {
    console.error('更新图表失败:', error)
  }
}

// 获取指标名称
const getMetricName = (metric) => {
  switch (metric) {
    case 'pm25':
      return 'PM2.5'
    case 'pm10':
      return 'PM10'
    case 'temperature':
      return '温度'
    case 'humidity':
      return '湿度'
    case 'formaldehyde':
      return '甲醛'
    default:
      return metric
  }
}

// 获取指标对应的y轴索引
const getYAxisIndex = (metric) => {
  switch (metric) {
    case 'pm25':
    case 'pm10':
      return 0
    case 'temperature':
    case 'humidity':
      return 1
    case 'formaldehyde':
      return 2
    default:
      return 0
  }
}

// 监听选择变化
watch([selectedSite, dateRange], () => {
  updateChart()
})

// 初始化数据
const initData = async () => {
  try {
    const [familyRes, roomRes, siteRes] = await Promise.all([
      getFamilyList(),
      getRoomList(),
      getSiteList()
    ])
    
    familyList.value = familyRes.data
    roomList.value = roomRes.data
    siteList.value = siteRes.data
    
    initChart()
    updateChart()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.chart-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-area {
  display: flex;
  gap: 10px;
}

.filter-select {
  width: 200px;
}

.date-picker {
  width: 300px;
}

.chart {
  height: 500px;
  width: 100%;
}
</style> 